//
//  SASearchShopNameView.m
//  saasRetail
//
//  Created by 黄志刚 on 2022/4/21.
//

#import "SASearchShopNameView.h"
#import "SASearchStoreUserCell.h"
#import "SASystemStoreStoreListAPI.h"
#import "SAStoreModel.h"

@interface SASearchShopNameView ()<UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate, HTTPAPIDelegate>

@property (nonatomic, strong) UITextField *searchTf;
@property (nonatomic, strong) UIButton *cancelBtn;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) UIView *tipView;
@property (nonatomic, strong) NSMutableArray *dataMarr;
@property (nonatomic, strong) SASystemStoreStoreListAPI *systemStoreStoreListAPI;

@end

@implementation SASearchShopNameView

+(instancetype)shareCornView
{
    SASearchShopNameView * shareView = [[SASearchShopNameView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
    return shareView;
}

-(instancetype)initWithFrame:(CGRect)frame {
    if(self = [super initWithFrame:frame]) {
        self.userInteractionEnabled = YES;
        self.backgroundColor = kColor(0, 0, 0, 0.6);
        [self creatUI];
    }
    return self;
}

#pragma mark - HTTPAPIDelegate
- (void)fetchData:(id)data fromServerSuccessedWithAPI:(HTTPAPI *)api {
    if (self.systemStoreStoreListAPI == api) {
        self.dataMarr = [SAStoreModel mj_objectArrayWithKeyValuesArray:data[@"data"]];
        SAStoreModel *model = nil;
        for (SAStoreModel *storeModel in self.dataMarr) {
            if (storeModel.merchantId == [SAValueManger shareInStance].userInfo.merchantId) {
                model = storeModel;
            }
        }
        if (model != nil) {
            [self.dataMarr removeObject:model];
        }
        
        [self.tableView reloadData];
        self.tipView.hidden = (self.dataMarr.count > 0);
    }
}

- (void)fetchDataFromServerFailedWithError:(NSError *)error API:(HTTPAPI *)api {
    NSDictionary *dic = error.userInfo;
    NSString *msg = [NSString stringWithFormat:@"%@",dic[@"msg"]];
    [Prompt popPromptViewWithMsg:msg duration:2];
}

#pragma mark - UITextFieldDelegate
- (void)textFieldEditChanged:(UITextField *)textField {
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(searchProduct2:) object:textField];
    [self performSelector:@selector(searchProduct2:) withObject:textField afterDelay:0.3];
}

- (void)searchProduct2:(UITextField *)textField {
    self.systemStoreStoreListAPI.keyword = textField.text;
    [self.systemStoreStoreListAPI sendRequestToServerWithActivityViewAndMask:GET];
}


#pragma mark - UITableView Delegate & DataSource
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataMarr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    SASearchStoreUserCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SASearchStoreUserCell" forIndexPath:indexPath];
    cell.storeModel = self.dataMarr[indexPath.row];
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    !self.selectBlock ?: self.selectBlock(self.dataMarr[indexPath.row]);
    [self confirmationTapEvent];
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return kScaleNum(36);
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [[UIView alloc] initWithFrame:CGRectZero];
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return kScaleNum(0.01);
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return SafeFooterHeight;
}

#pragma mark - event
-(void)clickedCancelBtn {
    
}

#pragma mark - initUI
-(void)creatUI {
    UIButton *deleteBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    deleteBtn.frame = CGRectMake(0, 0, kScaleNum(49), kScreenHeight);
    [deleteBtn addTarget:self action:@selector(shareDissTapEvent) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:deleteBtn];
    
    //需求改变，顶在最上面
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(kScaleNum(49), 0, kScreenWidth - kScaleNum(49), kScreenHeight)];
    whiteView.backgroundColor = [UIColor whiteColor];
    [self addSubview:whiteView];
    
    UIView *backGroundView = [[UIView alloc] initWithFrame:CGRectMake(kScaleNum(49), kScaleNum(20 + DifferenceHeight), kScreenWidth - kScaleNum(49), kScreenHeight - kScaleNum(20 + DifferenceHeight))];
    backGroundView.backgroundColor = [UIColor whiteColor];
    backGroundView.userInteractionEnabled = YES;
    [self addSubview:backGroundView];
    
    [backGroundView addSubview:self.searchTf];
    [backGroundView addSubview:self.cancelBtn];
    
    [backGroundView addSubview:self.tableView];
    UIView *line = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth - kScaleNum(49), kScaleNum(1))];
    line.backgroundColor = kLineColor;
    self.tableView.tableHeaderView = line;
    
    [backGroundView addSubview:self.tipView];
    
    self.systemStoreStoreListAPI.returnAll = @"false";
    [self.systemStoreStoreListAPI sendRequestToServerWithActivityViewAndMask:GET];
}

-(UITextField *)searchTf {
    if (!_searchTf) {
        _searchTf = [[UITextField alloc] initWithFrame:SARectMake(17, 7.5, 250, 30)];
        _searchTf.placeholder = @"请输入店铺名称";
        _searchTf.backgroundColor = kLineColor;
        _searchTf.layer.cornerRadius = kScaleNum(5);
        _searchTf.layer.masksToBounds = YES;
        _searchTf.delegate = self;
        _searchTf.font = kFont(14);
        _searchTf.clearButtonMode = UITextFieldViewModeWhileEditing;
        UIView *leftView = [[UIView alloc] initWithFrame:SARectMake(0, 0, 26, 30)];
        UIImageView *imageV = [[UIImageView alloc] initWithFrame:SARectMake(6, 7, 14, 16)];
        imageV.image = [UIImage imageNamed:@"shop_search"];
        [leftView addSubview:imageV];
        _searchTf.leftView = leftView;
        _searchTf.leftViewMode = UITextFieldViewModeAlways;
        [_searchTf addTarget:self action:@selector(textFieldEditChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    return _searchTf;
}

-(UIButton *)cancelBtn {
    if (!_cancelBtn) {
        _cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _cancelBtn.frame = CGRectMake(kScaleNum(267), 0, kScreenWidth - kScaleNum(316), kScaleNum(45));
        [_cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        [_cancelBtn setTitleColor:kGrayColor forState:UIControlStateNormal];
        _cancelBtn.titleLabel.font = kFont(15);
        [_cancelBtn addTarget:self action:@selector(shareDissTapEvent) forControlEvents:UIControlEventTouchUpInside];
    }
    return _cancelBtn;
}

-(UITableView *)tableView {
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, kScaleNum(45), kScreenWidth - kScaleNum(49), kScreenHeight - kScaleNum(45)) style:UITableViewStylePlain];
        if (@available(iOS 15.0, *)) {
            _tableView.sectionHeaderTopPadding = 0;
        }
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsHorizontalScrollIndicator = NO;
        _tableView.estimatedRowHeight = 0;
        _tableView.estimatedSectionHeaderHeight = 0;
        _tableView.estimatedSectionFooterHeight = 0;
        [_tableView registerClass:[SASearchStoreUserCell class] forCellReuseIdentifier:@"SASearchStoreUserCell"];
    }
    return _tableView;
}

-(NSMutableArray *)dataMarr {
    if (!_dataMarr) {
        _dataMarr = [NSMutableArray array];
    }
    return _dataMarr;
}

-(UIView *)tipView {
    if (!_tipView) {
        _tipView = [[UIView alloc] initWithFrame:CGRectMake(0, kScaleNum(45), kScreenWidth - kScaleNum(49), kScreenHeight - kScaleNum(45))];
        _tipView.backgroundColor = [UIColor whiteColor];
        _tipView.hidden = YES;
        UIImageView *icon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Shop_search2"]];
        icon.frame = CGRectMake((_tipView.width - kScaleNum(138))/2, kScaleNum(100), kScaleNum(138), kScaleNum(83));
        [_tipView addSubview:icon];
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(0, icon.maxY + kScaleNum(20), _tipView.width, kScaleNum(20))];
        titleLab.text = @"暂无相关信息";
        titleLab.textAlignment = NSTextAlignmentCenter;
        titleLab.textColor = kGrayColor;
        [_tipView addSubview:titleLab];
    }
    return _tipView;
}


- (void)showView:(UIViewController *)Sview
{
    if(Sview == nil){
        [[UIApplication sharedApplication].keyWindow addSubview:self];
    }else{
        [Sview.view addSubview:self];
    }
}

-(void)shareDissTapEvent
{
    [UIView animateWithDuration:0.5f animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(void)confirmationTapEvent
{
    [UIView animateWithDuration:0.5f animations:^{
        self.alpha = 0.0;
    } completion:^(BOOL finished) {
        [self removeFromSuperview];
    }];
}

-(SASystemStoreStoreListAPI *)systemStoreStoreListAPI {
    if (!_systemStoreStoreListAPI) {
        _systemStoreStoreListAPI = [SASystemStoreStoreListAPI apiWithDelegate:self];
    }
    return _systemStoreStoreListAPI;
}

@end
